/**
 * 分类管理服务模块
 *
 * 处理分类相关的数据操作逻辑
 */
const { Category } = require("../models");
const CustomError = require("../utils/CustomError");

class CategoryService {
  /**
   * 获取所有一级分类（parentId = 0）
   * @returns {Promise<Array>}
   */
  static async getTopLevelCategories() {
    return await Category.findAll({
      where: {
        parentId: 0
      },
      order: [
        ["sortOrder", "ASC"],
        ["id", "ASC"]
      ]
    });
  }

  /**
   * 获取完整的分类树
   * @returns {Promise<Array>}
   */
  static async getCategoryTree() {
    // 先获取所有分类
    const allCategories = await Category.findAll({
      order: [
        ["sortOrder", "ASC"],
        ["id", "ASC"]
      ]
    });

    // 构建分类树
    const categoryMap = {};
    const roots = [];

    // 初始化所有分类到map中
    allCategories.forEach(category => {
      categoryMap[category.id] = {
        ...category.toJSON(),
        children: []
      };
    });

    // 构建父子关系
    allCategories.forEach(category => {
      if (category.parentId === 0) {
        roots.push(categoryMap[category.id]);
      } else if (categoryMap[category.parentId]) {
        categoryMap[category.parentId].children.push(categoryMap[category.id]);
      }
    });

    return roots;
  }

  /**
   * 根据ID获取分类详情
   * @param {number} categoryId 分类ID
   * @returns {Promise<Object|null>}
   */
  static async getCategoryById(categoryId) {
    return await Category.findByPk(categoryId);
  }

  /**
   * 获取某个分类的直接子级
   * @param {number} parentId 父级分类ID
   * @returns {Promise<Array>}
   */
  static async getChildrenByParentId(parentId) {
    return await Category.findAll({
      where: {
        parentId: parentId
      },
      order: [
        ["sortOrder", "ASC"],
        ["id", "ASC"]
      ]
    });
  }

  /**
   * 创建新分类
   * @param {Object} categoryData 分类数据
   * @returns {Promise<Object>}
   */
  static async createCategory(categoryData) {
    return await Category.create(categoryData);
  }

  /**
   * 更新分类
   * @param {number} categoryId 分类ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<Object>}
   */
  static async updateCategory(categoryId, updateData) {
    const category = await Category.findByPk(categoryId);
    if (!category) {
      throw new CustomError(404, '分类不存在');
    }

    // 移除ID字段，防止更新ID
    delete updateData.id;

    return await category.update(updateData);
  }

  /**
   * 删除分类
   * @param {number} categoryId 分类ID
   * @returns {Promise<boolean>}
   */
  static async deleteCategory(categoryId) {
    const category = await Category.findByPk(categoryId);
    if (!category) {
      throw new CustomError(404, '分类不存在');
    }

    // 检查是否有子分类
    const childCount = await Category.count({
      where: {
        parentId: categoryId
      }
    });

    if (childCount > 0) {
      throw new CustomError(409, '存在子分类，无法删除');
    }

    await category.destroy();
    return true;
  }

  /**
   * 更新分类排序
   * @param {number} categoryId 分类ID
   * @param {number} sortOrder 排序值
   * @returns {Promise<Object>}
   */
  static async updateSortOrder(categoryId, sortOrder) {
    const category = await Category.findByPk(categoryId);
    if (!category) {
      throw new CustomError(404, '分类不存在');
    }

    return await category.update({ sortOrder });
  }
}

module.exports = CategoryService;